<template>
  <div class="register">
     <van-form @submit="onSubmit">
  <van-field
    v-model="formData.phone"
    placeholder="请输入手机号"
    :rules="[{ required: true, message: '请填写手机号' }]"
  />
  <van-field
    v-model="formData.pass"
    type="password"
    placeholder="请输入密码"
    :rules="[{ required: true, message: '请输入密码' }]"
  />
  <van-field
    v-model="formData.checkpass"
    type="password"
    placeholder="请再次输入密码"
    :rules="[{ required: true, message: '请再次输入密码' }]"
  />
  <div style="margin: 16px;">
    <van-button round block type="info" native-type="submit">注册</van-button>
  </div>
</van-form>
  </div>
</template>

<script>
import { Toast } from 'vant';
import { user_register } from "../utils/apis"
export default {
 data() {
    return {
       formData:{
        phone:'',
        pass:'',
        checkpass:''
       }
     
    };
  },
  methods: {
    onSubmit() {
     if( /^1[3-9]\d{9}$/.test( this.formData.phone ) == false ){
        alert('请输入合法的手机号');
      }else if( !this.formData.pass || !this.formData.checkpass ){
        alert('请输入密码/确认密码')
      }else if( this.formData.pass !== this.formData.checkpass){
        alert('密码和确认密码不一致');
      }else{ //验证通过 

        //深拷贝formData
        var newFormData = JSON.parse( JSON.stringify( this.formData ) );
        //删除对象的checkpass属性
        delete newFormData.checkpass;

        //发起注册请求
        user_register( newFormData ).then((res)=>{
          if( res.data.code == 200 ){ //注册成功
            Toast.success('注册成功!')
            //跳转到登录页
            this.$router.push('/login');
          }else{
            Toast.fail(res.data.msg)
          }
        })

      }
    },
  },
};
</script>

<style>

</style>